package ext.tianma.part.util.emailService;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;

import ext.com.iba.IBAUtil;
import ext.tianma.bom.service.QueryDocumentService;
import ext.tianma.bom.service.SelectPartService;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.doc.util.GetResearchSite;
import ext.tianma.util.IbaAttributeUtil;
import wt.doc.WTDocument;
import wt.fc.WTObject;
import wt.mail.EMailMessage;
import wt.pom.PersistenceException;
import wt.util.WTException;

/**
 * 用于DCC发布工艺文件以后,根据工艺文件的文档小类通知到对应人员
 * 
 * @author laichao_sun
 *
 */
public class DCCEmailNotification {
	public static String path = "/ptc/Windchill/codebase/ext/tianma/part/config/PartUpgradeEmailToSQE.xls";
	public static final String  moduleOrigin1  = "moduleOrigin";//生成地
	public static void emailNotification(WTObject object) {
		
		Workbook we = null;
		InputStream in = null;

		try {
			if (object instanceof WTDocument) {
				WTDocument doc = (WTDocument) object;

				in = new FileInputStream(path);
				we = WorkbookFactory.create(in);
				if (null == path || path.equals("")) {
					throw new WTException("没有获取到DCC发布工艺文件邮件提醒的配置路径，请检查!");
				}
				if (null == in || null == we) {
					throw new WTException("没有获取到DCC发布工艺文件邮件提醒的配置路径，请检查!");
				}
				// 生产地
				List<String> list = IbaAttributeUtil.getAttributeValues(doc, "moduleOrigin");
				List<String> list2 = new  ArrayList<String>();
				for(String s :list ) {
					String d = GetResearchSite.getEnumerationDisplayValue("地区",s);
					list2.add(d);
				}
				
				// 文档小类
				String SmallDocType = IbaAttributeUtil.getAttributeValue(doc, "SmallDocType");
			
				if (!(StringUtil.isNullOrEmpty(SmallDocType) && StringUtil.isNullOrEmpty(list2.toString()))) {
					String email = getCode(we.getSheetAt(1), list2, SmallDocType);
					//System.out.println("SLC ==邮箱,生产地,文档小类==> " + email + " | " + moduleOrigin + " | " + SmallDocType);
					if (!StringUtil.isNullOrEmpty(email)) {
						sendEmail(email, doc);
					}
				}
			}
		} catch (Exception e) {

		} finally {
			close(in);
		}

	}

	// 发送邮件
	private static void sendEmail(String emails, WTDocument doc) {
		try {
			
			// 测试邮箱内容
			//emails = "laichao_sun@tianma.cn";
			
			// 邮件内容
			StringBuffer body = new StringBuffer();
			String content = getContent(doc);
			body.append(content);
			String[] emailSendTo = "".equals(emails) || emails == null ? null : emails.split(";");// 2、why？
			EMailMessage email = EMailMessage.newEMailMessage();
			email.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			String titleStr = "PLM系统DCC发布邮件通知";
			title.append(titleStr);
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			email.send(false);
			
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	// 获取邮件内容
	private static String getContent(WTDocument doc) throws PersistenceException, WTException {
		String infoPage = "";

		String content = "";
		String name = doc.getName();
		String url =QueryDocumentService.generateInfoPageURL(doc);
		infoPage = "<a target='_blank' href='" + url + "'>" + name + "</a>";
		content = "<div style=\"width: 780px;padding: 15px;margin: 20px auto;border: 2px solid #33CCFF;border-top-width: 8px;text-align:left;\"><h2>PLM邮件提醒</h2><hr><div id=\"main-content\"><p>"
				+ "</p><p>你好，PLM提醒你：<br>PLM系统有工艺文件已DCC发布:" + infoPage + " 图纸请查看！<br></p></div></div>"
				+ getfoot();
		return content;
	}

	// 获取邮件下面的字段
	public static String getfoot() {
		String foot = "<div class=\"MsoNormal\"align=\"center\"style=\"text-align:center\"><span lang=\"EN-US\"style=\"font-size:12.0pt;font-family:宋体\"><hr size=\"2\"width=\"100%\"align=\"center\"></span></div><p class=\"MsoNormal\"align=\"left\"style=\"text-align:left\"><span style=\"font-size:9.0pt;font-family:宋体;color:gray\">“</span><span lang=\"EN-US\"style=\"font-size:9.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:gray\">This e-mail message together with any attachments thereto(if any)is confidential,intended only for the use of the named recipient(s)above.Any unauthorized review,use,copying,disclosure,or distribution of any information contained in or attached to this transmission is STRICTLY PROHIBITED.If you have received this message in error,or are not the named recipient(s),please immediately notify the sender and delete this e-mail message and any attached documentation from your computer.Thank you!<br></span><span style=\"font-size:9.0pt;font-family:宋体;color:gray\">本电子邮件及附件（如有）所载信息均为保密信息，仅供指定收件人使用。未经授权者收到此信息均无权阅读、使用、复制、揭露或散布。若您误收到本电子邮件或非本电子邮件的指定收件人，请立即通知发件人并从电脑中删除该电子邮件及其附件。谢谢！”</span></p>";
		return foot;
	}

	// 获取邮箱
	private static String getCode(Sheet sheet, List<String> list2, String smallDocType) {
		try {
			for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
				Row row = sheet.getRow(i);
				String temp = getCellValue(row.getCell(0)).trim();
				if (null == temp || temp.equals("")) {
					continue;
				} else {
					if (smallDocType.equals(temp)) {
						String temp2 = getCellValue(row.getCell(1)).trim();
						if (!StringUtil.isNullOrEmpty(temp2)) {
							if (list2.toString().contains(temp2)) {
								String email = getCellValue(row.getCell(2)).trim();
								return email;
							}

						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取单元格中的信息
	 * 
	 * @param cell 单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Double.toString(cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}

		return value.trim();
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
